<template>
  <div class="profile-page">
    <!-- 页面标题 -->
    <div class="page-header">
      <div class="header-content">
        <h1 class="page-title">个人中心</h1>
        <p class="page-description">管理您的个人信息和账户设置</p>
      </div>
    </div>

    <el-row :gutter="24">
      <!-- 左侧个人信息卡片 -->
      <el-col :span="8">
        <el-card class="profile-card">
          <template #header>
            <div class="card-header">
              <span>个人信息</span>
              <el-button type="text" @click="loadUserProfile" :loading="loading">
                <el-icon><Refresh /></el-icon>
              </el-button>
            </div>
          </template>
          
          <div class="profile-info" v-loading="loading">
            <!-- 头像区域 -->
            <div class="avatar-section">
              <el-avatar 
                :src="userProfile.avatar" 
                :size="120"
                class="profile-avatar"
              >
                <el-icon><User /></el-icon>
              </el-avatar>
              
              <el-upload
                class="avatar-uploader"
                :action="uploadAction"
                :headers="uploadHeaders"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :on-error="handleAvatarError"
                :before-upload="beforeAvatarUpload"
                accept="image/*"
              >
                <el-button type="primary" size="small" :loading="avatarUploading">
                  <el-icon><Upload /></el-icon>
                  更换头像
                </el-button>
              </el-upload>
            </div>
            
            <!-- 基本信息列表 -->
            <div class="info-list">
              <div class="info-item">
                <span class="label">用户ID:</span>
                <span class="value">{{ userProfile.userId || '-' }}</span>
              </div>
              <div class="info-item">
                <span class="label">用户名:</span>
                <span class="value">{{ userProfile.username || '-' }}</span>
              </div>
              <div class="info-item">
                <span class="label">真实姓名:</span>
                <span class="value">{{ userProfile.realName || '-' }}</span>
              </div>
              <div class="info-item">
                <span class="label">邮箱:</span>
                <span class="value">{{ userProfile.email || '-' }}</span>
              </div>
              <div class="info-item">
                <span class="label">手机号:</span>
                <span class="value">{{ userProfile.mobile || '-' }}</span>
              </div>
              <div class="info-item">
                <span class="label">状态:</span>
                <el-tag :type="userProfile.status === 1 ? 'success' : 'danger'" size="small">
                  {{ userProfile.status === 1 ? '正常' : '禁用' }}
                </el-tag>
              </div>
              <div class="info-item">
                <span class="label">角色:</span>
                <div class="roles-list">
                  <el-tag 
                    v-for="role in userProfile.roles" 
                    :key="role.id" 
                    size="small" 
                    class="role-tag"
                  >
                    {{ role.name }}
                  </el-tag>
                  <span v-if="!userProfile.roles || userProfile.roles.length === 0" class="no-data">
                    暂无角色
                  </span>
                </div>
              </div>
              <div class="info-item">
                <span class="label">分组:</span>
                <div class="groups-list">
                  <el-tag 
                    v-for="group in userProfile.groups" 
                    :key="group.id" 
                    type="info" 
                    size="small" 
                    class="group-tag"
                  >
                    {{ group.name }}
                  </el-tag>
                  <span v-if="!userProfile.groups || userProfile.groups.length === 0" class="no-data">
                    暂无分组
                  </span>
                </div>
              </div>
              <div class="info-item">
                <span class="label">创建时间:</span>
                <span class="value">{{ formatDateTime(userProfile.createTime) }}</span>
              </div>
              <div class="info-item">
                <span class="label">更新时间:</span>
                <span class="value">{{ formatDateTime(userProfile.updateTime) }}</span>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <!-- 右侧编辑区域 -->
      <el-col :span="16">
        <!-- 编辑个人资料 -->
        <el-card class="edit-card">
          <template #header>
            <div class="card-header">
              <span>编辑个人资料</span>
            </div>
          </template>
          
          <el-form
            ref="profileFormRef"
            :model="profileForm"
            :rules="profileRules"
            label-width="120px"
            class="profile-form"
          >
            <el-form-item label="真实姓名" prop="realName">
              <el-input 
                v-model="profileForm.realName" 
                placeholder="请输入真实姓名"
                clearable
              />
            </el-form-item>
            
            <el-form-item label="邮箱地址" prop="email">
              <el-input 
                v-model="profileForm.email" 
                placeholder="请输入邮箱地址"
                clearable
              />
            </el-form-item>
            
            <el-form-item label="手机号码" prop="mobile">
              <el-input 
                v-model="profileForm.mobile" 
                placeholder="请输入手机号码"
                clearable
              />
            </el-form-item>
            
            <el-form-item>
              <el-button 
                type="primary" 
                @click="handleSaveProfile" 
                :loading="profileSaving"
              >
                保存修改
              </el-button>
              <el-button @click="handleResetProfile">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
        
        <!-- 修改密码 -->
        <el-card class="password-card">
          <template #header>
            <div class="card-header">
              <span>修改密码</span>
              <el-text type="info" size="small">
                为了账户安全，请定期更换密码
              </el-text>
            </div>
          </template>
          
          <el-form
            ref="passwordFormRef"
            :model="passwordForm"
            :rules="passwordRules"
            label-width="120px"
            class="password-form"
          >
            <el-form-item label="原密码" prop="oldPassword">
              <el-input
                v-model="passwordForm.oldPassword"
                type="password"
                placeholder="请输入原密码"
                show-password
                clearable
              />
            </el-form-item>
            
            <el-form-item label="新密码" prop="newPassword">
              <el-input
                v-model="passwordForm.newPassword"
                type="password"
                placeholder="请输入新密码"
                show-password
                clearable
              />
              <div class="password-hint">
                <el-text type="info" size="small">
                  密码必须包含数字和字母，长度6-20位
                </el-text>
              </div>
            </el-form-item>
            
            <el-form-item label="确认新密码" prop="confirmPassword">
              <el-input
                v-model="passwordForm.confirmPassword"
                type="password"
                placeholder="请再次输入新密码"
                show-password
                clearable
              />
            </el-form-item>
            
            <el-form-item>
              <el-button 
                type="primary" 
                @click="handleChangePassword" 
                :loading="passwordChanging"
              >
                修改密码
              </el-button>
              <el-button @click="handleResetPassword">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { User, Upload, Refresh } from '@element-plus/icons-vue'
import { useUserStore } from '@/stores/user'
import { profileAPI } from '@/api/profile'
import { userAPI } from '@/api/user'

const userStore = useUserStore()
const profileFormRef = ref()
const passwordFormRef = ref()

// 加载状态
const loading = ref(false)
const profileSaving = ref(false)
const passwordChanging = ref(false)
const avatarUploading = ref(false)

// 用户详细信息
const userProfile = ref({
  userId: null,
  username: '',
  realName: '',
  email: '',
  mobile: '',
  avatar: '',
  status: 1,
  roles: [],
  groups: [],
  createTime: null,
  updateTime: null
})

// 个人资料表单
const profileForm = reactive({
  realName: '',
  email: '',
  mobile: ''
})

// 密码修改表单
const passwordForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 头像上传配置
const uploadAction = computed(() => '/api/user/avatar')
const uploadHeaders = computed(() => ({
  'Authorization': `Bearer ${localStorage.getItem('token')}`
}))

// 表单验证规则
const profileRules = {
  realName: [
    { required: true, message: '请输入真实姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '真实姓名长度在2-20个字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  mobile: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ]
}

// 密码强度验证函数
const validatePasswordStrength = (rule, value, callback) => {
  if (!value) {
    callback(new Error('请输入新密码'))
    return
  }
  
  if (value.length < 6 || value.length > 20) {
    callback(new Error('密码长度必须在6-20位之间'))
    return
  }
  
  const hasDigit = /\d/.test(value)
  const hasLetter = /[a-zA-Z]/.test(value)
  
  if (!hasDigit || !hasLetter) {
    callback(new Error('密码必须包含数字和字母'))
    return
  }
  
  callback()
}

// 确认密码验证函数
const validateConfirmPassword = (rule, value, callback) => {
  if (!value) {
    callback(new Error('请确认新密码'))
    return
  }
  
  if (value !== passwordForm.newPassword) {
    callback(new Error('两次输入的密码不一致'))
    return
  }
  
  callback()
}

const passwordRules = {
  oldPassword: [
    { required: true, message: '请输入原密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, validator: validatePasswordStrength, trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, validator: validateConfirmPassword, trigger: 'blur' }
  ]
}

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return '-'
  return new Date(dateTime).toLocaleString('zh-CN')
}

// 加载用户详细信息
const loadUserProfile = async () => {
  loading.value = true
  try {
    // 从用户存储中获取当前用户ID
    const userId = userStore.userInfo.userId
    if (!userId) {
      ElMessage.error('用户信息获取失败')
      return
    }

    const response = await userAPI.getUserById(userId)
    if (response.success) {
      const userVO = response.data || {}
      
      // 更新用户详细信息
      userProfile.value = {
        userId: userVO.user?.id || userId,
        username: userVO.user?.username || '',
        realName: userVO.user?.realName || '',
        email: userVO.user?.email || '',
        mobile: userVO.user?.mobile || '',
        avatar: userVO.user?.avatar || '',
        status: userVO.user?.status || 1,
        roles: userVO.roles || [],
        groups: userVO.groups || [],
        createTime: userVO.user?.createTime,
        updateTime: userVO.user?.updateTime
      }

      // 填充编辑表单
      profileForm.realName = userProfile.value.realName
      profileForm.email = userProfile.value.email
      profileForm.mobile = userProfile.value.mobile
    } else {
      ElMessage.error(response.message || '获取用户信息失败')
    }
  } catch (error) {
    console.error('获取用户信息失败:', error)
    ElMessage.error('获取用户信息失败')
  } finally {
    loading.value = false
  }
}

// 保存个人资料
const handleSaveProfile = async () => {
  if (!profileFormRef.value) return
  
  try {
    await profileFormRef.value.validate()
    profileSaving.value = true

    // 构建更新数据
    const updateData = {
      id: userProfile.value.userId,
      realName: profileForm.realName,
      email: profileForm.email,
      mobile: profileForm.mobile
    }

    const response = await userAPI.updateUser(updateData)
    if (response.success) {
      ElMessage.success('个人资料保存成功')
      
      // 更新本地用户信息
      userStore.userInfo.realName = profileForm.realName
      userStore.userInfo.email = profileForm.email
      
      // 重新加载用户信息
      await loadUserProfile()
    } else {
      ElMessage.error(response.message || '保存失败')
    }
  } catch (error) {
    console.error('保存个人资料失败:', error)
    ElMessage.error('保存失败，请稍后重试')
  } finally {
    profileSaving.value = false
  }
}

// 重置个人资料表单
const handleResetProfile = () => {
  profileForm.realName = userProfile.value.realName
  profileForm.email = userProfile.value.email
  profileForm.mobile = userProfile.value.mobile
  
  if (profileFormRef.value) {
    profileFormRef.value.clearValidate()
  }
}

// 修改密码
const handleChangePassword = async () => {
  if (!passwordFormRef.value) return
  
  try {
    await passwordFormRef.value.validate()
    
    // 确认操作
    await ElMessageBox.confirm(
      '修改密码后需要重新登录，确定要继续吗？',
      '确认修改',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    passwordChanging.value = true

    const response = await profileAPI.changeCurrentUserPassword({
      oldPassword: passwordForm.oldPassword,
      newPassword: passwordForm.newPassword,
      confirmPassword: passwordForm.confirmPassword
    })

    if (response.success) {
      ElMessage.success('密码修改成功，请重新登录')
      
      // 重置表单
      passwordForm.oldPassword = ''
      passwordForm.newPassword = ''
      passwordForm.confirmPassword = ''
      
      // 延迟登出，让用户看到成功消息
      setTimeout(() => {
        userStore.logout()
        window.location.href = '/login'
      }, 2000)
    } else {
      ElMessage.error(response.message || '密码修改失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('修改密码失败:', error)
      ElMessage.error('修改密码失败，请稍后重试')
    }
  } finally {
    passwordChanging.value = false
  }
}

// 重置密码表单
const handleResetPassword = () => {
  passwordForm.oldPassword = ''
  passwordForm.newPassword = ''
  passwordForm.confirmPassword = ''
  
  if (passwordFormRef.value) {
    passwordFormRef.value.clearValidate()
  }
}

// 头像上传前验证
const beforeAvatarUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!')
    return false
  }
  
  avatarUploading.value = true
  return true
}

// 头像上传成功
const handleAvatarSuccess = (response) => {
  avatarUploading.value = false
  
  if (response.success) {
    userProfile.value.avatar = response.data.avatarUrl
    userStore.userInfo.avatar = response.data.avatarUrl
    ElMessage.success('头像更新成功')
  } else {
    ElMessage.error(response.message || '头像上传失败')
  }
}

// 头像上传失败
const handleAvatarError = (error) => {
  avatarUploading.value = false
  console.error('头像上传失败:', error)
  ElMessage.error('头像上传失败，请稍后重试')
}

// 组件挂载时加载数据
onMounted(() => {
  loadUserProfile()
})
</script>

<style scoped>
/* 页面整体样式 */
.profile-page {
  padding: 0;
  background: transparent;
}

/* 页面标题 */
.page-header {
  margin-bottom: 24px;
}

.header-content {
  .page-title {
    font-size: 24px;
    font-weight: 600;
    color: #1f2937;
    margin: 0 0 8px 0;
  }
  
  .page-description {
    font-size: 14px;
    color: #6b7280;
    margin: 0;
  }
}

/* 卡片样式 */
.profile-card,
.edit-card,
.password-card {
  border-radius: 12px;
  border: 1px solid #e5e7eb;
  box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
  margin-bottom: 24px;
}

.password-card {
  margin-bottom: 0;
}

/* 卡片头部 */
.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-weight: 600;
  color: #1f2937;
}

/* 个人信息区域 */
.profile-info {
  padding: 8px 0;
}

.avatar-section {
  text-align: center;
  margin-bottom: 32px;
  padding: 16px 0;
}

.profile-avatar {
  margin-bottom: 16px;
  border: 4px solid #f3f4f6;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.avatar-uploader {
  display: block;
}

.avatar-uploader .el-button {
  border-radius: 20px;
  padding: 8px 16px;
  font-size: 13px;
}

/* 信息列表 */
.info-list {
  .info-item {
    display: flex;
    align-items: flex-start;
    margin-bottom: 20px;
    padding: 12px 0;
    border-bottom: 1px solid #f3f4f6;
    
    &:last-child {
      border-bottom: none;
      margin-bottom: 0;
    }
    
    .label {
      width: 90px;
      color: #6b7280;
      font-size: 14px;
      font-weight: 500;
      flex-shrink: 0;
      line-height: 1.5;
    }
    
    .value {
      flex: 1;
      font-size: 14px;
      color: #1f2937;
      line-height: 1.5;
      word-break: break-all;
    }
  }
}

/* 角色和分组标签 */
.roles-list,
.groups-list {
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
  align-items: center;
}

.role-tag,
.group-tag {
  margin: 0;
}

.no-data {
  color: #9ca3af;
  font-size: 13px;
  font-style: italic;
}

/* 表单样式 */
.profile-form,
.password-form {
  padding: 8px 0;
}

.profile-form .el-form-item,
.password-form .el-form-item {
  margin-bottom: 24px;
}

.profile-form .el-form-item:last-child,
.password-form .el-form-item:last-child {
  margin-bottom: 0;
}

/* 密码提示 */
.password-hint {
  margin-top: 6px;
}

/* 按钮样式 */
.el-button {
  border-radius: 8px;
  font-weight: 500;
}

.el-button + .el-button {
  margin-left: 12px;
}

/* 输入框样式 */
.el-input {
  --el-input-border-radius: 8px;
}

/* 标签样式 */
.el-tag {
  border-radius: 6px;
  font-weight: 500;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .profile-page {
    padding: 16px;
  }
  
  .el-col:first-child {
    margin-bottom: 24px;
  }
}

@media (max-width: 768px) {
  .profile-page {
    padding: 12px;
  }
  
  .page-header {
    margin-bottom: 20px;
  }
  
  .header-content .page-title {
    font-size: 20px;
  }
  
  .profile-avatar {
    width: 100px !important;
    height: 100px !important;
  }
  
  .info-list .info-item {
    flex-direction: column;
    align-items: flex-start;
    
    .label {
      width: auto;
      margin-bottom: 4px;
      font-weight: 600;
    }
  }
  
  .profile-form,
  .password-form {
    .el-form-item {
      margin-bottom: 20px;
    }
  }
}

/* 加载状态 */
.el-loading-mask {
  border-radius: 12px;
}

/* 卡片内容区域 */
:deep(.el-card__body) {
  padding: 24px;
}

:deep(.el-card__header) {
  padding: 20px 24px;
  border-bottom: 1px solid #f0f0f0;
}

/* 表单标签样式 */
:deep(.el-form-item__label) {
  font-weight: 500;
  color: #374151;
}

/* 上传组件样式 */
:deep(.el-upload) {
  display: block;
}

/* 头像上传按钮样式 */
.avatar-uploader :deep(.el-button) {
  display: flex;
  align-items: center;
  gap: 6px;
}

/* 状态标签样式 */
.el-tag.el-tag--success {
  background-color: #f0f9ff;
  border-color: #0ea5e9;
  color: #0ea5e9;
}

.el-tag.el-tag--danger {
  background-color: #fef2f2;
  border-color: #ef4444;
  color: #ef4444;
}

.el-tag.el-tag--info {
  background-color: #f8fafc;
  border-color: #64748b;
  color: #64748b;
}

/* 角色标签特殊样式 */
.role-tag {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  color: white;
}

.group-tag {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
  border: none;
  color: white;
}
</style>